import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-10-08
 * Time:9:21
 */

class Student {
    private String name;
    private int age;

    public Student() {

    }

    private Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void function(String str) {
        System.out.println(str);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

/**
 * 反射构造方法
 */
public class Demo1 {
    public static void reflectNewInstance() throws InstantiationException, IllegalAccessException {

        Class<?> c1 = Student.class;

        Student student = (Student) c1.newInstance();

        System.out.println(student);
    }

    /**
     * 反射私有的构造方法
     *
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static void reflectPrivateConstructor() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> c1 = Student.class;

        Constructor<?> constructor = c1.getDeclaredConstructor(String.class, int.class);

        constructor.setAccessible(true);

        Student student = (Student) constructor.newInstance("张三", 18);

        System.out.println(student);
    }

    public static void reflectPrivateField() throws InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> c1 = Student.class;

        Student student = (Student) c1.newInstance();

        Field field = c1.getDeclaredField("name");

        field.setAccessible(true);

        field.set(student,"张三");

        System.out.println(student);

    }

    public static void main(String[] args) {
        try {
            reflectNewInstance();
            reflectPrivateConstructor();
            reflectPrivateField();
        } catch (InstantiationException | IllegalAccessException
                | InvocationTargetException | NoSuchMethodException
                | NoSuchFieldException e) {
            e.printStackTrace();
        }


    }
}
